package file

import (
	"crypto/sha1"
	"encoding/hex"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
)

// GetSha1 获取文件sha1值
func GetSha1(filePath string) (sha1Str string, err error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := sha1.New()
	if _, err = io.Copy(hash, file); err != nil {
		return "", err
	}
	sha1Str = hex.EncodeToString(hash.Sum(nil))
	return sha1Str, nil
}

// GetFilesAllToChan 获取根路径下的所有文件
func GetFilesAllToChan(rootPath string, ch chan *Meta) error {
	paths, err := ioutil.ReadDir(rootPath)

	if err != nil {
		return err
	}

	for _, path := range paths {
		absPath := filepath.Join(rootPath, path.Name())
		// log.Println(absPath)
		fileInfo, err := os.Stat(absPath)
		if err != nil {
			return err
		} else if fileInfo.IsDir() {
			err = GetFilesAllToChan(absPath, ch)
			if err != nil {
				return err
			}
		} else {
			sha1Str, err := GetSha1(absPath)
			if err != nil {
				return err
			}
			meta := &Meta{
				Path:    absPath,
				Size:    fileInfo.Size(),
				Sha1:    sha1Str,
				ModTime: fileInfo.ModTime().Format("2006-01-02 15:04:05"),
			}
			// log.Println("send: ", absPath)
			ch <- meta
		}
	}

	return nil
}
